import tkinter as tk
from tkinter import filedialog, messagebox
from tkinter import ttk
from PIL import Image, ImageTk
import pandas as pd
import requests
import os
import io

class ImageViewerApp:
    def __init__(self, root):
        self.root = root
        self.root.title("图片查看器")
        self.root.geometry("600x600")
        self.root.configure(bg="#f0f0f0")  # 设置背景色

        # 初始化变量
        self.df = None
        self.current_index = -1
        self.filename = ""
        self.download_count = {}  # 记录每个文件名的下载序号

        # 创建 downloads 目录
        self.download_dir = "downloads"
        if not os.path.exists(self.download_dir):
            os.makedirs(self.download_dir)

        # 设置 ttk 主题
        style = ttk.Style()
        style.theme_use("clam")  # 使用 'clam' 主题，现代化外观
        style.configure("TButton", padding=6, font=("Arial", 10))
        style.configure("TLabel", font=("Arial", 12), background="#f0f0f0")
        style.configure("TFrame", background="#f0f0f0")

        # GUI 元素
        # 使用 ttk.Label
        self.label_filename = ttk.Label(root, text="文件名: ")
        self.label_filename.pack(pady=10)

        self.label_keyword = ttk.Label(root, text="关键词: ")
        self.label_keyword.pack(pady=10)

        # 图片显示区域
        self.image_label = tk.Label(root, bg="#f0f0f0")  # 使用 tk.Label 显示图片
        self.image_label.pack(pady=20)

        # 按钮框架
        button_frame = ttk.Frame(root)
        button_frame.pack(pady=10)

        # 使用 ttk.Button
        self.previous_button = ttk.Button(button_frame, text="上一个", command=self.show_previous)
        self.previous_button.pack(side=tk.LEFT, padx=10)

        self.download_button = ttk.Button(button_frame, text="下载", command=self.download_image)
        self.download_button.pack(side=tk.LEFT, padx=10)

        self.next_button = ttk.Button(button_frame, text="下一个", command=self.show_next)
        self.next_button.pack(side=tk.LEFT, padx=10)

        # 加载 Excel 文件
        self.load_excel()

    def load_excel(self):
        file_path = filedialog.askopenfilename(filetypes=[("Excel files", "*.xlsx *.xls")])
        if not file_path:
            messagebox.showerror("错误", "未选择文件！", parent=self.root)
            self.root.quit()
            return
        try:
            self.df = pd.read_excel(file_path)
            self.show_next()  # 显示第一行
        except Exception as e:
            messagebox.showerror("错误", f"无法读取 Excel 文件: {e}", parent=self.root)
            self.root.quit()

    def show_next(self):
        if self.df is None:
            return
        self.current_index += 1
        if self.current_index >= len(self.df):
            messagebox.showinfo("提示", "已完成所有筛选！", parent=self.root)
            self.current_index = len(self.df) - 1
            return

        # 获取当前行数据
        row = self.df.iloc[self.current_index]
        filename = row['文件名']
        keyword = row['关键词']
        image_url = row['图片链接']

        # 更新文件名和关键词
        self.filename = filename
        self.label_filename.config(text=f"文件名: {filename}")
        self.label_keyword.config(text=f"关键词: {keyword}")

        # 加载并显示图片
        try:
            response = requests.get(image_url, timeout=5)
            response.raise_for_status()
            image_data = response.content
            image = Image.open(io.BytesIO(image_data))
            image = image.resize((300, 300), Image.Resampling.LANCZOS)  # 调整图片大小
            self.photo = ImageTk.PhotoImage(image)
            self.image_label.config(image=self.photo)
        except Exception as e:
            self.image_label.config(image="")
            messagebox.showwarning("警告", f"无法加载图片: {e}", parent=self.root)

    def show_previous(self):
        if self.df is None:
            return
        self.current_index -= 1
        if self.current_index < 0:
            messagebox.showinfo("提示", "已经是第一张图片！", parent=self.root)
            self.current_index = 0
            return

        # 获取当前行数据
        row = self.df.iloc[self.current_index]
        filename = row['文件名']
        keyword = row['关键词']
        image_url = row['图片链接']

        # 更新文件名和关键词
        self.filename = filename
        self.label_filename.config(text=f"文件名: {filename}")
        self.label_keyword.config(text=f"关键词: {keyword}")

        # 加载并显示图片
        try:
            response = requests.get(image_url, timeout=5)
            response.raise_for_status()
            image_data = response.content
            image = Image.open(io.BytesIO(image_data))
            image = image.resize((300, 300), Image.Resampling.LANCZOS)  # 调整图片大小
            self.photo = ImageTk.PhotoImage(image)
            self.image_label.config(image=self.photo)
        except Exception as e:
            self.image_label.config(image="")
            messagebox.showwarning("警告", f"无法加载图片: {e}", parent=self.root)

    def download_image(self):
        if self.current_index < 0 or self.df is None:
            return
        row = self.df.iloc[self.current_index]
        image_url = row['图片链接']
        filename = row['文件名']

        # 计算下载序号
        if filename not in self.download_count:
            self.download_count[filename] = 1
        else:
            self.download_count[filename] += 1
        download_index = self.download_count[filename]

        # 下载图片
        try:
            response = requests.get(image_url, timeout=5)
            response.raise_for_status()
            save_path = os.path.join(self.download_dir, f"{filename}_{download_index}.jpg")
            with open(save_path, 'wb') as f:
                f.write(response.content)
            messagebox.showinfo("成功", f"图片已保存到 {save_path}", parent=self.root)
        except Exception as e:
            messagebox.showerror("错误", f"下载失败: {e}", parent=self.root)

if __name__ == "__main__":
    root = tk.Tk()
    app = ImageViewerApp(root)
    root.mainloop()